using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using System.Collections;
using System.Xml;
using System.Xml.Serialization;
/// <summary>
/// Various routines to help you build your site
/// </summary>
    public static class Utility {

        /// <summary>
        /// Returns a string located between two other strings.
        /// </summary>
        /// <param name="sVal">String value</param>
        /// <param name="startTag">starting string</param>
        /// <param name="EndTag">ending string</param>
        /// <returns></returns>
        public static string ParseString(string sVal,string startTag, string EndTag)
        {
            string sIn = sVal;
            string sOut = "";
            int tagStart = sIn.ToLower().IndexOf(startTag.ToLower());

            try
            {
                sIn = sIn.Remove(0, tagStart);
                sIn = sIn.Replace(startTag, "");
                int tagEnd = sIn.ToLower().IndexOf(EndTag.ToLower());

                string sName = sIn.Substring(0, tagEnd);

                sOut = sName;
            }
            catch
            {
            }
            return sOut;
        }
        /// <summary>
        /// Returns a Proper Cased value.
        /// </summary>
        /// <param name="sIn"></param>
        /// <returns></returns>
        public static string GetProperName(string sIn) {
            if (sIn != null)
            {
                if (sIn.Length > 1)
                {
                    string propertyName = sIn;
                    string leftOne = propertyName.Substring(0, 1).ToUpper();
                    propertyName = propertyName.Substring(1, propertyName.Length - 1);
                    propertyName = leftOne + propertyName;
                    if (propertyName.EndsWith("TypeCode")) propertyName = propertyName.Substring(0, propertyName.Length - 4);
                    return propertyName;
                }
            }
            return sIn;
        }
        /// <summary>
        /// Returns a camelCased word, Proper Cased with spacing
        /// </summary>
        /// <param name="sIn"></param>
        /// <returns></returns>
        public static string ParseCamelToProper(string sIn)
        {

            char[] letters=sIn.ToCharArray();
            string sOut = "";
            foreach (char c in letters)
            {
                if (c.ToString() != c.ToString().ToLower())
                {
                    //it's uppercase, add a space
                    sOut += " "+c.ToString();
                }
                else
                {
                    sOut += c.ToString();

                }
            }
            return sOut;
        }

        /// <summary>
        /// Returns the string value of an enum
        /// </summary>
        /// <param name="t"></param>
        /// <param name="Value"></param>
        /// <returns></returns>
        public static object StringToEnum(Type t, string Value)
        {
            object oOut = null;
            foreach (System.Reflection.FieldInfo fi in t.GetFields())
                if (fi.Name.ToLower() == Value.ToLower())
                    oOut = fi.GetValue(null);
            return oOut;
        }
        /// <summary>
        /// Random string generator
        /// </summary>
        /// <returns></returns>
        public static string GetRandomString()
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(RandomString(4, false));
            builder.Append(RandomInt(1000, 9999));
            builder.Append(RandomString(2, false));
            return builder.ToString();
        }
        private static int RandomInt(int min, int max)
        {
            Random random = new Random();
            return random.Next(min, max);
        }
        private static string RandomString(int size, bool lowerCase)
        {
            StringBuilder builder = new StringBuilder();
            Random random = new Random();
            char ch;
            for (int i = 0; i < size; i++)
            {
                ch = Convert.ToChar(Convert.ToInt32(26 * random.NextDouble() + 65));
                builder.Append(ch);
            }
            if (lowerCase)
                return builder.ToString().ToLower();
            return builder.ToString();
        }

        /// <summary>
        /// Returns the full, absolute URL of your site
        /// </summary>
        /// <returns></returns>
        public static string GetSiteRoot() {
            string Port = System.Web.HttpContext.Current.Request.ServerVariables["SERVER_PORT"];
            if (Port == null || Port == "80" || Port == "443")
                Port = "";
            else
                Port = ":" + Port;

            string Protocol = System.Web.HttpContext.Current.Request.ServerVariables["SERVER_PORT_SECURE"];
            if (Protocol == null || Protocol == "0")
                Protocol = "http://";
            else
                Protocol = "https://";

            string appPath = System.Web.HttpContext.Current.Request.ApplicationPath;
            if (appPath == "/")
                appPath = "";

            string sOut = Protocol + System.Web.HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + Port + appPath;
            return sOut;
        }

        /// <summary>
        /// Returns a string value for a QueryString parmeter. Returns empty if the value isn't there.
        /// </summary>
        /// <param name="sParam"></param>
        /// <returns></returns>
        public static string GetParameter(string sParam) {

            if (System.Web.HttpContext.Current.Request.QueryString[sParam] != null) {
                return System.Web.HttpContext.Current.Request[sParam].ToString();
            } else {
                return "";
            }

        }

        /// <summary>
        /// Returns an integer QueryString parameter. 0 if not present
        /// </summary>
        /// <param name="sParam"></param>
        /// <returns></returns>
        public static int GetIntParameter(string sParam) {
            int iOut = 0;
            if (System.Web.HttpContext.Current.Request.QueryString[sParam] != null) {
                string sOut = System.Web.HttpContext.Current.Request[sParam].ToString();
                if (!String.IsNullOrEmpty(sOut))
                    int.TryParse(sOut, out iOut);
            }
            return iOut;
        }
        
        /// <summary>
        /// Returns the text of a specified file
        /// </summary>
        /// <param name="virtualPath"></param>
        /// <returns></returns>
        public static string GetFileText(string virtualPath) {
            //Read from file
            StreamReader sr = null;
            try
            {
                sr = new StreamReader(System.Web.HttpContext.Current.Server.MapPath(virtualPath));
            }
            catch
            {
                sr = new StreamReader(virtualPath);

            }
            string strOut = sr.ReadToEnd();
            sr.Close();
            return strOut;
        }
        /// <summary>
        /// Updates the text in a file with the passed in values
        /// </summary>
        /// <param name="AbsoluteFilePath"></param>
        /// <param name="LookFor"></param>
        /// <param name="ReplaceWith"></param>
        public static void UpdateFileText(string AbsoluteFilePath, string LookFor, string ReplaceWith)
        {
            string sIn = GetFileText(AbsoluteFilePath);
            string sOut = sIn.Replace(LookFor, ReplaceWith);
            WriteToFile(AbsoluteFilePath, sOut);
        }
        /// <summary>
        /// Writes out a file
        /// </summary>
        /// <param name="AbsoluteFilePath"></param>
        /// <param name="fileText"></param>
        public static void WriteToFile(string AbsoluteFilePath, string fileText)
        {
            StreamWriter sw = new StreamWriter(AbsoluteFilePath, false);
            sw.Write(fileText);
            sw.Close();

        }

        public static int getID(string name)
        {
            string _id = string.Empty;
            return Convert.ToInt32(_id);

        }

        public static string getWebText(string keyname)
        {
            string _text = string.Empty;

            return _text;

        }

        #region Formatting bits
        #region CheckStringLength
        /// <summary>
        /// Checks a strings length
        /// </summary>
        /// <param name="stringToCheck"></param>
        /// <param name="maxLength"></param>
        /// <returns></returns>
        public static string CheckStringLength(string stringToCheck, int maxLength) {
            string checkedString = null;

            if (stringToCheck.Length <= maxLength)
                return stringToCheck;

            // If the string to check is longer than maxLength 
            // and has no whitespace we need to trim it down.
            if ((stringToCheck.Length > maxLength) && (stringToCheck.IndexOf(" ") == -1)) {
                checkedString = stringToCheck.Substring(0, maxLength) + "...";
            } else if (stringToCheck.Length > 0) {
                string[] words;
                int expectedWhitespace = stringToCheck.Length / 8;

                // How much whitespace is there?
                words = stringToCheck.Split(' ');

                checkedString = stringToCheck.Substring(0, maxLength) + "...";
            } else {
                checkedString = stringToCheck;
            }

            return checkedString;
        }

        #endregion

        #region FormatDate

        public static string FormatDate(DateTime theDate) {
            return FormatDate(theDate, false, null);
        }

        public static string FormatDate(DateTime theDate, bool showTime) {
            return FormatDate(theDate, showTime, null);
        }

        public static string FormatDate(DateTime theDate, bool showTime, string pattern) {
            string defaultDatePattern = "MMMM d, yyyy";
            string defaultTimePattern = "hh:mm tt";

            if (pattern == null) {
                if (showTime)
                    pattern = defaultDatePattern + " " + defaultTimePattern;
                else
                    pattern = defaultDatePattern;
            }

            return theDate.ToString(pattern);
        }

        #endregion

        #region UserIsAuthenticated

        public static bool UserIsAuthenticated() {
            HttpContext context = HttpContext.Current;

            if (context.User != null &&
                context.User.Identity != null &&
                !String.IsNullOrEmpty(context.User.Identity.Name)) {
                return true;
            }

            return false;
        }

        #endregion

        #region StripHTML

        public static string StripHTML(string htmlString) {
            return StripHTML(htmlString, "", true);
        }

        public static string StripHTML(string htmlString, string htmlPlaceHolder) {
            return StripHTML(htmlString, htmlPlaceHolder, true);
        }

        public static string StripHTML(string htmlString, string htmlPlaceHolder, bool stripExcessSpaces) {
            string pattern = @"<(.|\n)*?>";
            string sOut = System.Text.RegularExpressions.Regex.Replace(htmlString, pattern, htmlPlaceHolder);
            sOut = sOut.Replace("&nbsp;", "");
            sOut = sOut.Replace("&amp;", "&");

			if (stripExcessSpaces)
			{
				// If there is excess whitespace, this will remove
				// like "THE      WORD".
				char[] delim = { ' ' };
				string[] lines = sOut.Split(delim, StringSplitOptions.RemoveEmptyEntries);

				sOut = "";
				System.Text.StringBuilder sb = new System.Text.StringBuilder();
				foreach (string s in lines)
				{
					sb.Append(s);
					sb.Append(" ");
				}
				return sb.ToString().Trim();
			}
			else
			{
				return sOut; 
			}

        }

        #endregion

        #region ToggleHtmlBR

        public static string ToggleHtmlBR(string text, bool isOn) {
            string outS = "";

            if (isOn)
                outS = text.Replace("\n", "<br />");
            else {
                // TODO: do this with via regex
                //
                outS = text.Replace("<br />", "\n");
                outS = text.Replace("<br>", "\n");
                outS = text.Replace("<br >", "\n");
            }

            return outS;
        }

        #endregion

        #endregion

    }
